package com.dylan.历史.基础;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * Created by Dylan on 2018/9/5.
 */
public class 反射_泛型 {

    public static void main(String[] args) {
        new Sub1().handle("你好");
        new Sub2().handle(520);
    }

    static class Base<T> {
        void handle(T t) {
            // 通过反射获取泛型的实际类型
            Class[] clzArr = getGenericClassType(this.getClass());
            System.out.println("当前类型是：" + clzArr[0].getName());
            System.out.println("当前的值是：" + t);
        }
    }

    static class Sub1 extends Base<String> {

    }

    static class Sub2 extends Base<Integer> {

    }

    static Class[] getGenericClassType(Class clz) {
        Type superclass = clz.getGenericSuperclass();
        if (superclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) superclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            Class[] clzArr = Arrays.stream(actualTypeArguments)
                    .filter(type -> type instanceof Class)
                    .map(t -> (Class) t)
                    .toArray(Class[]::new);
            if (clzArr.length == 0) {
                throw new TypeNotPresentException(clz.getTypeName(), null);
            }
            return clzArr;
        }
        throw new TypeNotPresentException(clz.getTypeName(), null);
    }
}
